import { ref, reactive, toRefs } from "vue"

/**
 * @params fn 要向服务器请求的api函数
 * @params searchParams  搜索的参数
 * 
 * 
 */

type IParams = {
    pageNum: number,
    pageSize: number
}

export default function useTable<T extends { list: any[], total: number }, P extends IParams = IParams>(fn: (params: P) => IRES<T>, searchParams?: Object) {

    // 分页参数
    const params = reactive<IParams>({
        pageNum: 1,
        pageSize: 10
    })

    const list = ref<(T['list'])>([])
    const total = ref(0)

    const fetch = () => {
        fn({ ...(params as P), ...searchParams }).then((res) => {
            if (res.code === 200) {
                list.value = res.data.list
                total.value = res.data.total
            }
        })
    }
    fetch()

    // 单独每个方法可以拓展业务逻辑
    const sizeChangeFn = () => {
        fetch()
    }

    const currentChangeFn = () => {
        fetch()
    }

    // 搜索功能
    const searchFn = () => {
        fetch()
    }

    return {
        list,
        ...toRefs(params),
        total,
        sizeChangeFn,
        currentChangeFn,
        searchFn

    }
}